// index.ts
// 获取应用实例
const app = getApp<IAppOption>()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Component({
  data: {
    motto: 'Hello World',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },
  methods: {
    // 事件处理函数
    bindViewTap() {
      wx.navigateTo({
        url: '../logs/logs',
      })
    },
    bindViewSM() {
      wx.navigateTo({
        url: '../main/main',
      })
    },
    /** 进入游戏记录界面 */
    toPageGameRecord() {
      wx.navigateTo({
        url: '../game-record/logs',
      })
    },
    onChooseAvatar(e: any) {
      const { avatarUrl } = e.detail
      const { nickName } = this.data.userInfo
      this.setData({
        "userInfo.avatarUrl": avatarUrl,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
    },
    onInputChange(e: any) {
      const nickName = e.detail.value
      const { avatarUrl } = this.data.userInfo
      this.setData({
        "userInfo.nickName": nickName,
        hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
      })
    },
    getUserProfile() {
      // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
      wx.getUserProfile({
        desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          console.log(res)
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    },

    // 微信小程序看广告
    watchAdvertisements() {
      const rewardedVideoAd = wx.createRewardedVideoAd({
        // adUnitId: 'xxxxxxx'
        adUnitId: 'adunit-4418253632447072'
      })
      rewardedVideoAd.show().catch(() => {
        rewardedVideoAd.load()
          .then(() => rewardedVideoAd.show())
          .catch(err => {
            console.log(err)
            console.log('激励视频 广告显示失败')

            wx.showToast({
              title: "激励视频 广告显示失败",
              icon: 'none',
              duration: 3000
            })
          })
      })
      rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      })
      rewardedVideoAd.onClose((res) => {
        if (res && res.isEnded) {
          // 正常播放结束，可以下发奖励
          rewardedVideoAd.offClose() //--------------重点：清除上一次回调，避免产生重复回调

          //调用接口、处理逻辑
          wx.showToast({
            title: "观看成功",
            icon: 'success',
            duration: 3000
          })
        } else {
          wx.showToast({
            title: "失败",
            icon: 'none',
            duration: 3000
          })
        }
      })

    }
  },
})
